/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from "react";
import StandardTable from "@/components/StandardTable";
import { Form, Button, Row, Col, message } from "antd";
import { connect } from "dva";
import { debounce } from "lodash";
import ChangeFeeModal from "../components/modal";

const FormItem = Form.Item;

@connect(({ loading, dispat }) => ({
  dispat,
  getDistributionList: loading.effects["dispat/getDistributionList"],
  getDistributionDetail: loading.effects["dispat/getDistributionDetail"],
  storageFeeReleaseBatch: loading.effects["dispat/storageFeeReleaseBatch"],
  storageFeeRelease: loading.effects["dispat/storageFeeRelease"],
  storageCheckBalance: loading.effects["dispat/storageCheckBalance"],
}))
export default class FeeDistribute extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      type: "",
      confirmLoading: false,
      recordValue: {},
      page: 1,
    };
    this.giveOutColumns = [
      {
        title: "入库时间",
        dataIndex: "region",
        key: "region",
      },
      {
        title: "未发放金额（元）",
        dataIndex: "frozen_fee",
        key: "frozen_fee",
        render: text => {
          return <span style={{ color: "red" }}>{text}</span>;
        },
      },
      {
        title: "已发放金额（元）",
        dataIndex: "send_fee",
        key: "send_fee",
      },
      {
        title: "核减金额（元）",
        dataIndex: "deduct_fee",
        key: "deduct_fee",
      },
      {
        render: (text, record) => {
          return record.frozen_fee > 0 ? (
            <Button
              type="primary"
              onClick={this.showModal.bind(this, { type: "distribution", recordValue: record })}
            >
              发放
            </Button>
          ) : null;
        },
      },
    ];
  }

  componentDidMount() {
    this.getList();
  }

  onStandardTableChange = debounce(
    pagination => {
      const {
        dispatch,
        fromValues: { beginMonth, endMonth },
        detailRecord: { to_kb_id },
      } = this.props;

      this.setState({ page: pagination.current });

      dispatch({
        type: "dispat/getDistributionDetail",
        payload: {
          toKbId: to_kb_id,
          beginMonth,
          endMonth,
          page: pagination.current,
        },
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    }
  );

  getList() {
    const { dispatch, detailRecord, fromValues } = this.props;
    const { beginMonth, endMonth } = fromValues;
    const { to_kb_id } = detailRecord;
    const { page } = this.state;

    dispatch({
      type: "dispat/getDistributionDetail",
      payload: {
        toKbId: to_kb_id,
        beginMonth,
        endMonth,
        page,
      },
    });
  }

  showModal = ({ type, recordValue }) => {
    this.setState({
      visible: true,
      type,
      recordValue,
    });
  };

  saveFormRef = formRef => {
    this.formRef = formRef;
  };

  handleCancel = () => {
    const {
      form: { resetFields },
    } = this.formRef.props;
    resetFields();
    this.setState({
      visible: false,
      confirmLoading: false,
    });
  };

  handleOk = () => {
    const { dispatch } = this.props;
    const { recordValue } = this.state;
    const { form } = this.formRef.props;
    this.setState({ confirmLoading: true });

    form.validateFields((err, value) => {
      const { to_kb_id, region, frozen_fee } = recordValue;
      const { sendFee, deductFee } = value;
      if (err) {
        this.setState({ confirmLoading: false });
        return;
      }

      // 校验金额
      if (sendFee * 1 + deductFee * 1 > frozen_fee * 1) {
        message.error("发放金额+核减金额不得大于冻结金额，请修改后重新发放");
        this.setState({
          visible: true,
          confirmLoading: false,
        });
      } else if (!sendFee && !deductFee) {
        this.setState({
          visible: false,
          confirmLoading: false,
        });
      } else {
        dispatch({
          type: "dispat/storageFeeRelease",
          payload: {
            toKbId: to_kb_id,
            region,
            sendFee,
            deductFee,
          },
        }).then(() => {
          this.getList();
        });
        this.setState({
          visible: false,
          confirmLoading: false,
        });
        form.resetFields();
      }
    });
  };

  render() {
    const {
      dispat: { distributionDetail },
      hideGiveOut,
      getDistributionDetail,
      detailRecord: { inn },
    } = this.props;
    const {
      visible,
      type,
      confirmLoading,
      recordValue: { frozen_fee },
    } = this.state;

    return (
      <div>
        <FormItem>
          <h2>保管费发放</h2>
          <Row type="flex">
            <Col>
              所选驿站：
              {inn}
            </Col>
            <Col offset={1}>
              <Button type="primary" onClick={hideGiveOut}>
                返回
              </Button>
            </Col>
          </Row>
        </FormItem>
        <StandardTable
          loading={getDistributionDetail}
          rowKey={record => record.id}
          data={distributionDetail}
          columns={this.giveOutColumns}
          onChange={this.onStandardTableChange}
        />
        <ChangeFeeModal
          type={type}
          frozenFee={frozen_fee}
          title="保管费发放"
          wrappedComponentRef={this.saveFormRef}
          visible={visible}
          onCancel={this.handleCancel}
          onCreate={this.handleOk}
          confirmLoading={confirmLoading}
        />
      </div>
    );
  }
}
